<?php
declare (strict_types=1);

namespace app\admin\controller\wechat;

use app\common\controller\BaseController;
use app\admin\model\wechat\Article as ArticleModel;
use app\admin\model\wechat\Account as AccountModel;

use app\common\library\wechat\Crawler;
use think\facade\Cache;

class Article extends BaseController
{

    /**
     * @var ArticleModel
     */
    protected $model;
    /**
     * @var AccountModel
     */
    private $AccountModel;

    public function initialize()
    {
        parent::initialize();

        $this->model = new ArticleModel;
        $this->AccountModel = new AccountModel;
    }

    public function download()
    {
        $id = $this->request->param('id', 0, 'intval');
        $article = $this->model->where('id', '=', $id)->find();
        if (!$article) {
            return $this->error('文章不存在');
        }
        $crawler = new Crawler();

        $html = $crawler->getMsgContent($article['link']);
        $html = str_replace("//res.wx.qq.com", "https://res.wx.qq.com", $html);
        $html = str_replace("/mp/videoplayer", "https://mp.weixin.qq.com/mp/videoplayer", $html);

        $filepath = "./storage/account/{$article['a_nickname']}/{$article['title']}.html";
        $dir = dirname($filepath);
        if (file_exists($dir) == false) {
            mkdir($dir, 0777, true);
        }

        $result = file_put_contents($filepath, $html);

        $url = $this->request->domain() . trim($filepath, '.');

        return $this->success('请求成功', $url);
    }

    public function syncArticle()
    {
        $fakeid = $this->request->param('fakeid', '', 'trim');
        $account = $this->AccountModel->where('fakeid', '=', $fakeid)->find();
        if (!$account) {
            return $this->error('公众号不存在');
        }
        $key = 'wechat_sync_article';
        $cache = Cache::get($key);
        if (empty($cache)) {
            Cache::set($key, $fakeid, 10);
            //微信采集队列
            $queueData = [
                'type' => 'latest',
                'alias' => $account['alias'],
                'fakeid' => $account['fakeid'],
                'source' => 'sync'
            ];
            add_wechat_queue($queueData);

            $this->success('操作成功');
        } else {
            $this->error('操作频繁，请稍后再试');
        }
    }

}